package com.hbut.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "RoleFilter",urlPatterns = {"/*"})
public class RoleFilter implements Filter {
    public void destory(){}
    //主要的方法，实现对request、response进行过滤操作
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //实现请求对象、响应对象的强制类型转换
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取用户请求对象中包含的请求资源路径
        String uri = request.getRequestURI();
        if (uri.contains("login")) {
            chain.doFilter(req, resp);
        }else {
            HttpSession session = request.getSession();
            Object user = session.getAttribute("userInfo");
            if (user == null) {
                response.sendRedirect("./login.jsp");
            }else {
                chain.doFilter(req, resp);
            }
        }


    }
    //拦截对象在被初始化时调用的方法
    public void init(FilterConfig fConfig) throws ServletException {

    }


}
